﻿using BCGM.MedicalWisdom.Extensions;
using BCGM.MedicalWisdom.IServices;
using BCGM.MedicalWisdom.Model;
using BCGM.MedicalWisdom.Model.Models;
using BCGM.MedicalWisdom.Model.ViewModels.DoctorDTO;
using BCGM.MedicalWisdom.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace BCGM.MedicalWisdom.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    /// <summary>
    ///     患者用户表注册
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class DoctorUsersController : ControllerBase
    {
        private readonly IDoctorUsersServices _doctorUsersServices;

        private ISession MySession => HttpContext.Session;
        private readonly IRedisBasketRepository _redisBasketRepository;
        public DoctorUsersController(IDoctorUsersServices doctorUsersServices,IRedisBasketRepository redisBasketRepository)
        {
            _doctorUsersServices=doctorUsersServices;
            _redisBasketRepository=redisBasketRepository;
        }
        
        [HttpGet]
        [AllowAnonymous]
        public async Task GetCode(string phone)
        {
            Random random = new Random();
            string yz = random.Next(111111,999999).ToString();
            //给Key值赋值
            string key = phone;

            if (phone.Length == 11)
            {
                var qwe = await _redisBasketRepository.Exist(key);
                if (qwe == true)
                {
                    return;
                }
                else
                {
                    //通过阿里云发送验证码
                    //AliSendSms.send(phone, yz);
                    //存入redis
                    await _redisBasketRepository.Set(key,yz,TimeSpan.FromSeconds(300));
                }
            }
        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> UserAdds(DoctorUsersDTO input)
        {
            var data = new MessageModel<string>();
            //从redis获取到缓存的验证码
            string ph = await _redisBasketRepository.Get<string>(input.mobile_number);
            if (ph != input.validate_code)
            {
                data.success=false;
                data.msg="验证码错误！";
                return data;
            }
            var counts = await _doctorUsersServices.Query(d=>d.mobile_number==input.mobile_number);
            if (counts.Count()>0)
            {
                data.msg="该手机号已经注册";
                return data;
            }
            //添加此数据，返回受影响行数
            var id = await _doctorUsersServices.UserAdds(input);
            data.success=id>0;
            if (data.success)
            {
                data.response=id.ObjToString();
                data.msg="添加成功";
                
            }
            return data;
        }
    }
}
